package com.jhf.youke.core.utils;


import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.JWTParser;
import com.nimbusds.jwt.SignedJWT;
import lombok.SneakyThrows;

import java.util.Map;

/**
 * @author RHJ
 * **/
public class JwtHelper {
    private static JWSHeader header = initJwsHeader();

    @SneakyThrows
    public static String generate(Map<String, Object> payload, String sign){
        var claim = JWTClaimsSet.parse(new JSONObject(payload));
        var token = new SignedJWT(header, claim);
        token.sign(new MACSigner(sign));
        return token.serialize();
    }

    @SneakyThrows
    public static Map<String, Object> getPayload(String jwt){
        return JWTParser.parse(jwt).getJWTClaimsSet().getClaims();
    }

    @SneakyThrows
    private static JWSHeader initJwsHeader(){
        return JWSHeader.parse("{\"typ\": \"JWT\", \"alg\": \"HS256\"}");
    }
}
